<template>
  <div id="audio" ref="audio" v-if="loadState" :class="{audio_background:FilePath}" :style="containerStyle"
       @dblclick.stop="loadAudio">
    <img class="audio_image" src="~@/assets/img/SlideEditor/music.png" v-if="FilePath" :style="imageStyle"
         :class="{audio_animation:isPlay}" draggable="false"/>
    <audio :ref="`audio_file_${ID}`" v-if="FilePath" :controls="isShowToolBar" :muted="isPlayVolume"
           :autoplay="isAutoPlay" @play="audioConfigChange" @pause="audioConfigChange">
      <source :src="getFilePath(FilePath,'AUDIO')"/>
    </audio>
    <img v-else class="open_file" title="打开" src="~@/assets/img/SlideEditor/audio_icon.png" draggable="false"
         @click="loadAudio">
  </div>
  <img v-else class="loading" src="~@/assets/img/SlideEditor/Navigation/loading.gif" draggable="false">

</template>
<script>
import {mapActions, mapGetters} from 'vuex'
import action from '../../common/typeActions'
import ipcs from '../../common/typeIpcs'
import path from 'path'
import uuid from 'uuid/v4'

let remote = ''
let fsextra = ''


export default {
  name: 'Audio',
  props: {
    ID: {type: String},
    FilePath: {type: String},
    FileCode: {type: String},
    isShowToolBar: {type: Boolean, default: false},
    isPlayVolume: {type: Boolean, default: false},
    isAutoPlay: {type: Boolean, default: false},
    containerStyle: {type: Object},
    containerSize: {type: Object},
    isPlayFile: {type: Boolean, default: false},
    isReadonly: {type: Boolean, default: false}
  },
  data: function () {
    return {
      imageStyle: null,
      isPlay: false,
      loadState: true
    }
  },
  computed: {
    ...mapGetters(['getFilePath', 'caseFolder'])
  },
  watch: {
    containerSize: function (n, o) {
      this.init()
    },
    isPlayFile: function (n, o) {
      let audio = this.$refs[`audio_file_${this.ID}`]
      if (!audio) return
      if (n) {
        audio.play()
      } else {
        audio.pause()
      }
    }
  },
  mounted: function () {
    this.init()
  },
  methods: {
    ...mapActions({
      addExternalFile: action.SLIDEEDITOR.AddExternalFile,
      setElementAttr: action.SLIDEEDITOR.SetElementAttr
    }),
    init: function () {
      this.$nextTick(function () {
        try {
          let audio = this.$refs.audio
          if (!audio) return
          let elSize = {
            width: audio.offsetWidth,
            height: audio.offsetHeight
          }
          let style = {}

          if (!this.isPlayVolume) elSize.height -= 32

          if (elSize.width === elSize.height) {
            style.width = style.height = elSize.height
          } else if (elSize.width > elSize.height) {
            style.width = style.height = elSize.height
          } else {
            style.width = style.height = elSize.width
          }

          style['border-radius'] = style.width * 0.5 + 'px'
          style.left = (elSize.width - style.width) / 2 + 'px'
          style.top = (elSize.height - style.height) / 2 + 'px'
          style.width += 'px'
          style.height += 'px'
          this.imageStyle = style
        } catch (error) {
          console.error(error)
          this.$alert(error.message, '初始化音频时错误', {type: 'error'})
        }
      })
    },
    // 上传音频文件
    loadAudio: function () {
      let self = this
      if (self.isReadonly) return

      if (remote) {
        let extensions = {
          properties: ['openFile', 'showHiddenFiles'],
          filters: [{name: 'Audio', extensions: ['mp3']}]
        }
        remote.dialog.showOpenDialog(
            remote.getCurrentWindow(),
            extensions,
            async rs => {
              try {
                if (!rs) return
                self.loadState = false

                let {ext} = path.parse(rs[0])
                let toPath = path.join(this.caseFolder(), uuid() + ext)
                // 移动文件到案件文件夹下
                fsextra.copySync(rs[0], toPath)
                await this.addExternalFile({
                  id: self.ID,
                  fileID: self.FileCode,
                  imageID: self.FilePath,
                  path: toPath
                })
                // self.$emit("AudioLoadFinish", self.ID);
                self.loadState = true
              } catch (error) {
                self.$alert(error.message, '提示', {type: 'warning'})
              }
            }
        )
      } else {
        let input = document.createElement('input')
        input.type = 'file'
        input.multiple = false
        input.accept = 'audio/*'
        input.onchange = async () => {
          if (event.target.files.length > 0) {
            this.loadState = false
            if (!/mp3/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择MP3格式的音频文件')
            let formData = new FormData()
            formData.append('dbPath', this.$store.state.appearCourt.casePath)
            for (let i = 0; i < event.target.files.length; i++) {
              formData.append('files', event.target.files[i])
            }
            let uploadFiles = await this.$api.post.uploadFiles(formData)
            await this.addExternalFile({
              id: this.ID,
              fileID: this.FileCode,
              imageID: this.FilePath,
              file: uploadFiles[0]
            })
            // this.$emit('AudioLoadFinish', {ID: this.ID, Path: uploadFiles[0].FilePath})
            this.loadState = true
          }
        }
        input.click()

        // let extensions = {
        //   accept: 'audio/*',
        //   multiple: false
        // }
        // this.openFileDialog(extensions, async () => {
        //   if (event.target.files.length > 0) {
        //     try {
        //       if (!/mp3/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择MP3格式的音频文件')
        //       /* eslint-disable new-cap */
        //       let uploadFileBySlice = new this.$methods.uploadFileBySlice({
        //         file: event.target.files[0],
        //         fileType: 'caseAccessory'
        //       })
        //       // uploadFileBySlice.eventBus.on('progress', progress => {
        //       //   console.log('进度条:', progress)
        //       // });
        //       uploadFileBySlice.eventBus.on('success', async data => {
        //         await this.addExternalFile({
        //           id: this.ID,
        //           fileID: this.FileCode,
        //           imageID: this.FilePath,
        //           path: { Files: [data] }
        //         })
        //         // this.$emit("AudioLoadFinish", this.ID);
        //         this.loadState = true
        //       })
        //       uploadFileBySlice.eventBus.on('fail', err => {
        //         this.$alert(err.message, '错误', { type: 'error' })
        //         this.loadState = true
        //       })
        //
        //       this.loadState = false
        //       uploadFileBySlice.start()
        //     } catch (error) {
        //       this.$alert(error.message, '提示')
        //     }
        //   }
        // })
      }
    },
    audioConfigChange: function (param) {
      if (!this.isShowToolBar) return
      if (param.type !== 'pause' && param.type !== 'play') return
      // 获取音频播放组件
      let audio = this.$refs[`audio_file_${this.ID}`]
      if (!audio) return
      this.isPlay = param.type !== 'pause'
    }
  }
}
</script>
<style>
#audio {
  width: 100%;
  height: 100%;
}

#audio audio {
  width: 100%;
  height: 100%;
}

#audio source {
  width: 100%;
  height: 100%;
}

.audio_background {
  background: url("~@/assets/img/SlideEditor/audio_bg.jpg");
  background-size: 100% 100%;
  position: relative;
}

#audio .audio_image {
  position: absolute;
  top: 0;
  left: 0;
  height: calc(100% - 32px);
}

#audio .open_file {
  position: absolute;
  top: calc(50% - 16px);
  left: calc(50% - 16px);
  cursor: pointer;
}

#audio .audio_animation {
  transform: rotate(0deg);
  animation: play 15s linear infinite;
}

@-webkit-keyframes play {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading {
  width: 100%;
  height: 100%;
}
</style>
